<template>
  <div class="devices flex-column h-100P w-100P">
    <div class="flex">
      <CustomButton @click="handleUnbundling()" title="批量解绑"></CustomButton>
    </div>
    <div class="flex-sub mg-top-20" style="max-height: 50vh;">
      <el-table
        :data="tableData"
        v-loading="loading"
        height="98%"
        header-cell-class-name="table-header-cell"
        header-row-class-name="table-header-row"
        @selection-change="handleSelectionChange"
        row-key="id"
        ref="table"
      >
        <el-table-column :reserve-selection="true" type="selection" width="45"></el-table-column>
        <el-table-column prop="deviceVo.name" label="设备编号"></el-table-column>
        <el-table-column prop="deviceVo.remarkName" label="设备名称"></el-table-column>
        <el-table-column prop="abilityName" label="算法名称"></el-table-column>
        <!--        <el-table-column prop="productName" label="所属产品"></el-table-column>-->
        <!--        <el-table-column prop="netTypeEnum" label="入网类型"></el-table-column>-->
        <el-table-column prop="online" label="在线状态">
          <template v-slot="{row}">
            <span class="offline" :class="{online: row.deviceVo.online}">
              {{ row.deviceVo.online ? '在线' : '离线' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="activeTime" label="最近在线时间">
          <template v-slot="{row}">
            {{ row.activeTime|dateTimeFormatter }}
          </template>
        </el-table-column>
        <el-table-column label="算法任务开/关">
          <template slot-scope="{row}">
            <div class="align-center">
              <el-switch
                v-model="row.working"
                active-color="#67C23A"
                @change="handleChangeTaskStatus(row)"
              />
              <span class="mg-left-10">{{ row.dataStatusName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="160">
          <template slot-scope="{row}">
            <el-button
              type="text"
              size="mini"
              class="link-text fz-14"
              @click="handleUnbundling(row.id)"
            >
              解绑
            </el-button>
          </template>
        </el-table-column>
        <template v-slot:empty>
          <img :src="emptyImage" alt="" />
        </template>
      </el-table>
    </div>
    <el-pagination
      hide-on-single-page
      background
      layout="prev, pager, next, total, jumper"
      :total="queryInfo.total"
      :page-size="queryInfo.pageSize"
      @current-change="handlePageNoChange"
    />
  </div>
</template>

<script>
import { apiStartTask, apiStopTask } from '@/views/algorithm/alg-task/api'
import { apiFindDevicePageByParam, apiDelAbilityDeviceBatch } from './api'
import CustomButton from '@/components/custom-button'

export default {
  name: 'Devices',
  props: {
    ability: {
      type: Object,
      require: true,
      default: () => ({}),
    },
  },
  components: {
    CustomButton,
  },
  data() {
    return {
      loading: false,
      queryInfo: {
        pageSize: 14,
        pageNo: 1,
        total: 0,
      },
      tableData: [],
      selectedDevicesList: [],
    }
  },
  created() {
    this.initPage()
  },
  computed: {
    emptyImage() {
      return `${this.$consts.OSS_STATIC_IMAGE_URL}/empty.png`
    },
  },
  methods: {
    initPage() {
      this.queryInfo.abilityId = this.$route.query.abilityId
      this.handleSearch()
    },
    handlePageNoChange(pageNo) {
      this.queryInfo.pageNo = pageNo
      this.handleSearch()
    },
    handleSelectionChange(val) {
      this.selectedDevicesList = val
    },
    handleCheck(device) {
      this.$router.push({
        path: '/device/deploy-device-detail',
        query: { deviceId: device.deviceVo.id },
      })
    },
    handleSearch() {
      this.findDevice()
    },
    /**
     * 改变设备的任务状态
     */
    handleChangeTaskStatus({ id: id, working }) {
      const handleSuccess = () => {
        this.$message.success('状态切换成功')
        // this.handleSearch()
      }

      if (working) {
        apiStartTask(id).then(() => handleSuccess())
      } else {
        apiStopTask(id).then(() => handleSuccess())
      }
    },

    async findDevice() {
      this.loading = true
      const { total, pageSize, pageNo, records } = await apiFindDevicePageByParam(this.queryInfo)
      this.tableData = records
      this.queryInfo.pageSize = pageSize
      this.queryInfo.pageNo = pageNo
      this.queryInfo.total = total
      this.loading = false
    },

    handleUnbundling(id) {
      const tipMessage = id ? '解绑' : '批量解绑'
      const abilityDeviceIds = id ? [id] : this.selectedDevicesList.map(item => item.id)
      if (!abilityDeviceIds.length) return this.$message.warning('请先选择设备才能进行批量解绑')
      this.$confirm(`您确定要${tipMessage}当前设备`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        try {
          await apiDelAbilityDeviceBatch(abilityDeviceIds)

          this.$message.success(`${tipMessage}成功`)
          this.handleSearch()
        } catch (error) {
          console.log('handleUnbundling happen error：', error)
        }
        this.$refs.table.clearSelection()
      })
    },
  },
}
</script>

<style scoped lang="scss">
.devices {
  padding: vw(20px);
  box-sizing: border-box;

  .offline {
    color: #d12d1f;
  }

  .online {
    color: rgb(103, 194, 58);
  }
}
</style>
